<template>
  <div>
    <el-card class="box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
      >
        添加品牌
      </el-button>
      <!-- 表格组件，展示品牌信息
    border 纵向边框
    label 列标题
    width:列宽
    align:对齐 
    -->
      <el-table style="margin: 10px 0px" border :data="trademarkArr">
        <el-table-column label="序号" width="80px" align="center" type="index">
          <template #="{ row, $index }">
            <pre style="color: brown">{{ row.id }}</pre>
          </template>
        </el-table-column>
        <!-- table-column默认使用div展示 -->
        <el-table-column label="品牌名称">
          <template #="{ row, $index }">
            <pre style="color: brown">{{ row.tmName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img
              :src="row.logoUrl"
              alt="没有图片"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}吗？`"
              width="250px"
              icon="Delete"
              @confirm="removeTrademark(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 
    pagination
      v-model:current-page 设置分页器当前页码 
      v-model:page-size 设置每页展示数据条数
      page-sizes：设置下拉菜单数量
      background: 分页按钮背景
      layout 设置分页器6个子组件布局调整
    -->
      <el-pagination
        @size-change="sizeChange"
        @current-change="getHasTrademark"
        :page-count="Math.floor(total / limit)"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
      />
    </el-card>

    <!-- 对话框组件：添加品牌和修改已有品牌使用 -->
    <!-- v-model控制对话框显示和隐藏
    title 对话框 左上角标题
   -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
          <!-- upload属性
          action 上传图片请求地址 需携带api
          
          -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
//引入组合式API函数ref
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqHasTrademark } from '@/api/product/trademark'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type'

import { ElMessage, type UploadProps } from 'element-plus'
import {
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '../../../api/product/trademark'

//当前页码
let pageNo = ref<number>(1)
//每一页展示多少数据
let limit = ref<number>(3)

//存储已有品牌的总数
let total = ref<number>(0)

//存储已有品牌的数组
let trademarkArr = ref<Records>([])
//控制对话框显示和隐藏
let dialogFormVisible = ref<boolean>(false)

//定义收集品牌的数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})

let formRef = ref()

//获取已有品牌封装函数
const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  console.log('ddddddddd', result)
  if (result.code == 200) {
    total.value = result.data.total
    // console.log(result)
    trademarkArr.value = result.data.records
  }
}

//组件挂载完毕钩子-发一次请求，获取第一页,一页三个已有品牌数据
onMounted(() => {
  getHasTrademark()
})

//分页器页面发生变化
//回传了当前页码
// const changePageNo = () => {
//   //当前页码发生变化，再次发请求获取数据
//   getHasTrademark()
// }

//当下拉菜单发生变化的时候会触发
const sizeChange = () => {
  //页面变化归一
  // pageNo.value = 1;
  getHasTrademark()
}

//添加品牌按钮回调
const addTrademark = () => {
  dialogFormVisible.value = true
  //清空收集数据
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''

  //清理校验结果
  //第一种写法
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

//修改品牌按钮回调
const updateTrademark = (row: TradeMark) => {
  //清空校验信息
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })

  // console.log(row)
  dialogFormVisible.value = true
  //ES6语法:合并两个对象
  Object.assign(trademarkParams, row)
  //添加id属性标识是修改
  // trademarkParams.id = row.id
  // //展示已经有品牌数据
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
}

//对话框取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}

const confirm = async () => {
  //在发请求前，对整个表单校验，校验通过再进行后面的语法
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  //添加或修改
  if (result.code == 200) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //再次发请求获取全部品牌数据
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    //添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    dialogFormVisible.value = false
  }
}

//上传图片之前触发钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //在图片上传成功之前触发，约束文件类型和大小
  //要求：文件格式png,jpg,gif, 大小<4M
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件大小必须小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件格式必须是png,jpg,gif',
    })
    return false
  }
}

//图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  //response 上传图片返回的数据
  //收集上传图片的地址，添加一个新品牌带给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功，清除校验结果
  formRef.value.clearValidate('logoUrl')
}

//品牌自定义校验规则
const validatorTmName = (rule: any, value: any, callBack: any) => {
  //当表达元素触发blur时
  console.log(value)
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack() //校验通过
  } else {
    //校验未通过，返回错误信息
    callBack(new Error('品牌名称位数大于等于2位'))
  }
}

//品牌logo图片自定义校验
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //图片上传
  if (value) {
    callBack()
  } else {
    callBack(new Error('logo图片务必上传'))
  }
}

//表单校验规则对象
const rules = {
  tmName: [
    //required必须校验，出现红色五角星
    //trigger触发时机
    { required: true, trigger: 'blur', validator: validatorTmName },
  ],
  logoUrl: [{ required: true, trigger: 'change', validator: validatorLogoUrl }],
}

const removeTrademark = async (id: number) => {
  //点击确定按钮删除已有品牌请求
  let result = await reqDeleteTrademark(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    //再次获取品牌数据
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
